package com.ktgj.train.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.TrainConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.TrainEnum;
import com.ktgj.common.core.utils.HttpClientUtil;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.customer.api.domain.CustomeraccountApi;
import com.ktgj.train.domain.GenerateOrder;
import com.ktgj.train.domain.InterfaceEntity.TrCancelChangeRequest;
import com.ktgj.train.domain.InterfaceEntity.TrCancelChangeResponse;
import com.ktgj.train.domain.InterfaceEntity.*;
import com.ktgj.train.domain.SeatPrice;
import com.ktgj.train.domain.TrainOrder;
import com.ktgj.train.domain.trainlist.*;
import com.ktgj.train.service.ITrainOrderService;
import com.ktgj.train.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.alibaba.druid.util.Utils.md5;

@Service
public class TrainTicketsImpl implements TrainTickets {

    String TRAIN = "train:";

    @Autowired
    private ITrainOrderService trainOrderService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    /**
     * MD5加密
     * @param value
     * @return
     */
    private String signMsgs(String value) {
        StringBuilder builder = new StringBuilder();
        builder.append(value);
        String md5 = md5(builder.toString());
        md5.toLowerCase();
        return md5;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String reqtime = dateFormat.format(new Date());

    //余票查询
    @Override
    public TrRemainingTicketResponse queryByTrainTickets(TrRemainingTicketRequest request) {
//        String fromStationName = request.fromStationName;
//        String toStationName = request.toStationName;
//        String trainDate = request.train_date;
//        String redisKey = fromStationName + toStationName + trainDate;
//        Object cacheObject = redisService.getCacheObject(TRAIN + redisKey);
//        if (cacheObject != null) {
//            String str = JSON.toJSONString(cacheObject);
//            Object parse = JSON.parse(str);
//            TrRemainingTicketResponse response = JSON.parseObject(parse.toString(), TrRemainingTicketResponse.class);
//            return response;
//        } else {
            String keyMd5 = md5(UserUtils.key);
            StringBuilder builder = new StringBuilder();
            builder.append(UserUtils.partnerID);
            builder.append(UserUtils.query_method);
            builder.append(reqtime);
            builder.append(keyMd5);
            String sign = signMsgs(builder.toString());
            Map<String, Object> map = new HashMap<>();
            map.put("partnerid", UserUtils.partnerID);
            map.put("method", UserUtils.query_method);
            map.put("reqtime", reqtime);
            map.put("sign", sign);
            map.put("train_date", request.train_date);
            map.put("fromStationName", request.fromStationName);
            map.put("toStationName", request.toStationName);
            map.put("purpose_codes", "ADULT");
            String jsonStr = JSON.toJSONString(map);
            Map<String, String> mapParam = new HashMap<>();
            mapParam.put("jsonStr", jsonStr);
            String post = HttpClientUtil.doPost(UserUtils.ticketUrl, mapParam);
            TrRemainingTicketResponse response = JSON.parseObject(post, TrRemainingTicketResponse.class);
//            if (response != null && response.data.size() > 0) {
//                redisService.setCacheObject(TRAIN + redisKey, JSON.toJSONString(response), 1L, TimeUnit.DAYS);
//            }
        if (response.success) {
            for (TrainList datum : response.data) {
                if (datum.from_station_name.equals(request.fromStationName)){
                    datum.fromStationSite = "originate";
                }
                else {
                    datum.fromStationSite = "passingBy";
                }

                if (datum.from_station_name.equals(request.toStationName)){
                    datum.toStationSite = "end";
                }
                else {
                    datum.toStationSite = "passingBy";
                }

                datum.edzName = "edz";
                datum.ydzName = "ydz";
                datum.swzName = "swz";
                datum.tdzName = "tdz";
                datum.yzName = "yz";
                datum.ywName = "yw";
                datum.rwName = "rw";
                datum.gjrwName = "gjrw";
                datum.wzName = "wz";
                datum.rzName = "rz";
                datum.dwName = "dw";
            }

            if (request.type != null){
                List<TrainList> originate = new ArrayList<>();
                List<TrainList> passingBy = new ArrayList<>();

                for (TrainList datum : response.data) {
                    if (datum.from_station_name.equals(request.fromStationName)){
                        originate.add(datum);
                    }
                    else {
                        passingBy.add(datum);
                    }
                }

                if (request.type.equals("true")){
                    response.data = originate;
                }
                else {
                    response.data = passingBy;
                }
            }
        }
        return response;
//        }
    }

    @Override
    public TrainList queryTrainSeat(QueryTrainSeatRequest request) {
        TrRemainingTicketRequest ticketRequest = new TrRemainingTicketRequest();
        ticketRequest.fromStationName = request.fromStationName;
        ticketRequest.toStationName = request.toStationName;
        ticketRequest.train_date = request.train_date;
        TrRemainingTicketResponse response = queryByTrainTickets(ticketRequest);
        List<TrainList> list = new ArrayList<>();
        for (TrainList trainList : response.data) {
            trainList.strTime = request.train_date;
            if (request.train_code.equals(trainList.train_code)) {
                list.add(trainList);
            }
        }
        for (TrainList trainList : list) {
            if (request.fromStationName.equals(trainList.from_station_name) && request.toStationName.equals(trainList.to_station_name)) {
                return trainList;
            }
        }
        return null;
    }

    //获取指定座位价格
    @Override
    public BigDecimal seatPrice(SeatPrice price) {
        QueryTrainSeatRequest request = new QueryTrainSeatRequest();
        request.fromStationName = price.fromStationName;
        request.toStationName = price.toStationName;
        request.train_date = price.train_date;
        request.train_code = price.train_code;
        TrainList trainList = queryTrainSeat(request);
        float seatPrice = 0;
        if (price.seat.equals(TrainEnum.edz.getValue())) {
            seatPrice = trainList.edz_price;
        } else if (price.seat.equals(TrainEnum.ydz.getValue())) {
            seatPrice = trainList.ydz_price;
        } else if (price.seat.equals(TrainEnum.swz.getValue())) {
            seatPrice = trainList.swz_price;
        } else if (price.seat.equals(TrainEnum.tdz.getValue())) {
            seatPrice = trainList.tdz_price;
        } else if (price.seat.equals(TrainEnum.yz.getValue())) {
            seatPrice = trainList.yz_price;
        } else if (price.seat.equals(TrainEnum.yw.getValue())) {
            seatPrice = trainList.yw_price;
        } else if (price.seat.equals(TrainEnum.rw.getValue())) {
            seatPrice = trainList.rw_price;
        } else if (price.seat.equals(TrainEnum.gjrw.getValue())) {
            seatPrice = trainList.gjrw_price;
        } else if (price.seat.equals(TrainEnum.wz.getValue())) {
            seatPrice = trainList.wz_price;
        } else if (price.seat.equals(TrainEnum.rz.getValue())) {
            seatPrice = trainList.rz_price;
        } else if (price.seat.equals(TrainEnum.dw.getValue())) {
            seatPrice = trainList.dwx_price;
        }
        BigDecimal decimal = BigDecimal.valueOf(seatPrice);
        return decimal;
    }

    //订单提交（申请占座）
    @Override
    public TrOrderSubmissionResponse orderSubmission(TrOrderSubmissionRequest request) {
        TrainOrder trainOrder = new TrainOrder();
        List<Passengers> list = new ArrayList<>();
        TrOrderSubmissionResponse response = null;
        double price = 0;
        String zwcode = "";
        String passengersename = "";
        String phoneNum = "";
        try {
            for (Passengers information : request.passengers) {
                passengersename = information.passengersename; //乘客姓名
                String passportseno = information.passportseno; //乘客证件号
                String passporttypeseidname = information.passporttypeseidname; //乘客证件类型名
                String passporttypeseid = information.passporttypeseid; //乘客证件类型CODE
                information.passengerid = reqtime; //乘客唯一标识（字符串内为随机长数字，例如: "567572342534583365256"）
                String zwname = information.zwname; //坐席名
                zwcode = information.zwcode; //坐席类型CODE
                price = information.price; //票价(这里必填，不了解则传 "0")
                String piaotype = information.piaotype; //票类型
                String cxin = information.cxin; //传空字符串
                phoneNum = information.phoneNum; //手机号
                list.add(information);
            }

            String keyMd5 = md5(UserUtils.key);
            StringBuilder builder = new StringBuilder();
            builder.append(UserUtils.partnerID);
            builder.append(UserUtils.order_method);
            builder.append(reqtime);
            builder.append(keyMd5);
            String sign = signMsgs(builder.toString());

            Map<String, Object> map = new HashMap<>();
            map.put("callbackurl", UserUtils.trainOrderCallback);
            map.put("reqtime", reqtime);
            map.put("from_station_name", request.from_station_name);
            map.put("checi", request.checi);
            map.put("to_station_name", request.to_station_name);
            map.put("LoginUserName", UserUtils.trainAccount);
            map.put("LoginUserPassword", UserUtils.trainPassword);
            map.put("partnerid", UserUtils.partnerID);
            map.put("train_date", request.train_date);
            map.put("method", UserUtils.order_method);
            map.put("reqtoken", reqtime);
            map.put("orderid", request.orderid);
            map.put("guestPay", "1");
            map.put("sign", sign);
            map.put("passengers", list);

            String jsonStr = JSON.toJSONString(map);

            Map<String, String> mapParam = new HashMap<>();
            mapParam.put("jsonStr", jsonStr);

            String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
            response = JSON.parseObject(post, TrOrderSubmissionResponse.class);
            return response;
        } catch (Exception e) {
            response.msg = "创建订单失败";
        }
        return response;
    }

    @Override
    public TrOrderSubmissionResponse orderSubmissions(GenerateOrder request) {
        List<Passengers> list = new ArrayList<>();
        TrOrderSubmissionResponse response = null;
        try {
            for (Passengers information : request.passengers) {
                list.add(information);
            }

            String keyMd5 = md5(UserUtils.key);
            StringBuilder builder = new StringBuilder();
            builder.append(UserUtils.partnerID);
            builder.append(UserUtils.order_method);
            builder.append(reqtime);
            builder.append(keyMd5);
            String sign = signMsgs(builder.toString());

            Map<String, Object> map = new HashMap<>();
            map.put("callbackurl", UserUtils.trainOrderCallback);
            map.put("reqtime", reqtime);
            map.put("from_station_name", request.from_station_name);
            map.put("checi", request.checi);
            map.put("to_station_name", request.to_station_name);
            map.put("LoginUserName", request.LoginUserName);
            map.put("LoginUserPassword", request.LoginUserPassword);
            map.put("partnerid", UserUtils.partnerID);
            map.put("train_date", request.train_date);
            map.put("method", UserUtils.order_method);
            map.put("reqtoken", request.reqtoken);
            map.put("choose_seats", request.choose_seats);
            map.put("orderid", request.orderid);
            map.put("guestPay", "1");
            map.put("sign", sign);
            map.put("passengers", list);

            String jsonStr = JSON.toJSONString(map);

            Map<String, String> mapParam = new HashMap<>();
            mapParam.put("jsonStr", jsonStr);

            String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
            response = JSON.parseObject(post, TrOrderSubmissionResponse.class);
            return response;
        } catch (Exception e) {
            response.msg = "创建订单失败";
        }
        return response;
    }

    //确认出票
    @Override
    public TrOutTicketResponse outTicket(TrOutTicketRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.confirm_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());

        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.confirm_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("transactionid", request.transactionid);
        map.put("orderid", request.orderid);
        map.put("callbackurl", UserUtils.trainConfirmCallback);

        String jsonStr = JSON.toJSONString(map);

        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);

        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);

        TrOutTicketResponse response = JSON.parseObject(post, TrOutTicketResponse.class);

        return response;
    }

    //取消订单
    @Override
    public TrCancellationOrderResponse cancellationOrder(TrCancellationOrderRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.cancel_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());

        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.cancel_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("transactionid", request.transactionid);
        map.put("orderid", request.orderid);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);

        TrCancellationOrderResponse trCancellationOrderResponse = JSON.parseObject(post, TrCancellationOrderResponse.class);
        return trCancellationOrderResponse;
    }

    //订单信息查询
    @Override
    public TrOrderQueryResponse orderQuery(TrOrderQueryRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.query_info_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.query_info_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("orderid", request.orderid);
        map.put("transactionid", request.transactionid);

        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);

        TrOrderQueryResponse response = JSON.parseObject(post, TrOrderQueryResponse.class);

        return response;
    }

    //请求改签
    @Override
    public TrTicketChangesResponse trainRequestChange(TrTicketChangesRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.request_change_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.request_change_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("orderid", request.orderid);
        map.put("transactionid", request.transactionid);
        map.put("ordernumber", request.ordernumber);
        map.put("change_checi", request.change_checi);
        map.put("change_datetime", request.change_datetime);
        map.put("change_zwcode", request.change_zwcode);
        map.put("old_zwcode", request.old_zwcode);
        map.put("isasync", request.isasync);
        map.put("callbackurl", UserUtils.trainRequestChangeCallback);
        map.put("reqtoken", request.reqtoken);
        map.put("from_station_name", request.from_station_name);
        map.put("to_station_name", request.to_station_name);

        List<TicketInfo> ticketInfoList = new ArrayList<>();
        for (TicketInfo ticketinfo : request.ticketinfo) {
            ticketInfoList.add(ticketinfo);
        }
        map.put("ticketinfo", ticketInfoList);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrTicketChangesResponse response = JSON.parseObject(post, TrTicketChangesResponse.class);
        return response;
    }

    /**
     * 获取支付链接给客人支付
     * @param request
     * @return
     */
    @Override
    public TrainPaymentResponse trainPayment(TrainPaymentRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.payment_link_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.payment_link_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("orderid", request.getOrderid());
        map.put("paymentChannel", request.getPaymentChannel());
        map.put("linkType", request.getLinkType());
        map.put("businessType", request.getBusinessType());
        map.put("callbackurl", UserUtils.trainConfirmCallback);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrainPaymentResponse response = JSON.parseObject(post, TrainPaymentResponse.class);
        return response;
    }

    //支付状态同步
    @Override
    public TrPayStatusSynchResponse payStatusSynch(TrPayStatusSynchRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.status_synch_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.status_synch_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("orderid", request.orderid);
        map.put("success", request.success);
        map.put("type", request.type);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrPayStatusSynchResponse response = JSONObject.parseObject(post, TrPayStatusSynchResponse.class);
        return response;
    }

    @Override
    public TrainTransitResponse trainTransit(TrainTransitRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.train_info_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.train_info_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("train_date", request.getTrain_date());
        map.put("fromStationName", request.getFromStationName());
        map.put("toStationName", request.getToStationName());
        map.put("train_no", request.getTrain_no());
        map.put("train_code", request.getTrain_code());
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.ticketUrl, mapParam);
        TrainTransitResponse response = JSON.parseObject(post, TrainTransitResponse.class);
        if (response.isSuccess() && response.getData().size() > 0) {
            for (Transit datum : response.getData()) {
                if (datum.getData().size() > 0) {
                    for (Transits datumDatum : datum.getData()) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String startTime = request.getTrain_date() + " " + datumDatum.getStart_time();
                        try {
                            Date startParse = dateFormat.parse(startTime);
                            if (datumDatum.getArrive_days() > 0) {
                                Calendar calendar = new GregorianCalendar();
                                calendar.setTime(startParse);
                                calendar.add(Calendar.DATE, datumDatum.getArrive_days());
                                startParse = calendar.getTime();
                            }
                            Date date = new Date();
                            boolean before = date.before(startParse);
                            if (before)
                                datumDatum.setAfter(false);
                            else
                                datumDatum.setAfter(true);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return response;
    }

    //12306账号验证（登录）
    @Override
    public RelationValidateResponse relationValidate(String token, RelationValidateRequest request) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("trainAccount", request.getTrainAccount());
        maps.put("pass", request.getPass());
        Map<String, Object> map = new HashMap<>();
        String encode = "";
        try {
            encode = encodeData(JSON.toJSONString(maps));
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("data", encode);
        map.put("accountversion", "2");
        String jsonStr = JSON.toJSONString(map);
        String post = HttpClientUtil.doPostXmlStream(UserUtils.accountValidateUrl, jsonStr);
        RelationValidateResponse response = JSON.parseObject(post, RelationValidateResponse.class);
        if (token != null) {
            R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
            if (customer.getCode() == 200) {
                Long customerId = customer.getData().getCustomerId();
                R<CustomeraccountApi> customeraccountApiR = remoteCustomerService.queryAccountIdAndAccountPassword(customerId, CustomerConstants.trianAccount.getValue());
                if (customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() != null) {
                    if (response.isSuccess() == true) {
                        CustomeraccountApi customerAccount = new CustomeraccountApi();
                        customerAccount.setAccountId(request.getTrainAccount());
                        customerAccount.setAccountPassword(request.getPass());
                        customerAccount.setAccountType(CustomerConstants.trianAccount.getValue());
                        customerAccount.setCustomerId(customerId);
                        remoteCustomerService.updateAccountPassword(customerAccount);
                    }
                } else if (customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() == null) {
                    if (response.isSuccess() == true) {
                        CustomeraccountApi customerAccount = new CustomeraccountApi();
                        customerAccount.setAccountId(request.getTrainAccount());
                        customerAccount.setAccountPassword(request.getPass());
                        customerAccount.setAccountType(CustomerConstants.trianAccount.getValue());
                        customerAccount.setCustomerId(customerId);
                        customerAccount.setCreateTime(new Date());
                        remoteCustomerService.insert(customerAccount);
                    }
                }
            }
        } else {
            R<CustomeraccountApi> customeraccountApiR = remoteCustomerService.queryAccountIdAndAccountPassword(Long.valueOf(request.getCustomerId()), CustomerConstants.trianAccount.getValue());
            if (customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() != null) {
                if (response.isSuccess() == true) {
                    CustomeraccountApi customerAccount = new CustomeraccountApi();
                    customerAccount.setAccountId(request.getTrainAccount());
                    customerAccount.setAccountPassword(request.getPass());
                    customerAccount.setAccountType(CustomerConstants.trianAccount.getValue());
                    customerAccount.setCustomerId(Long.valueOf(request.getCustomerId()));
                    remoteCustomerService.updateAccountPassword(customerAccount);
                }
            } else if (customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() == null) {
                if (response.isSuccess() == true) {
                    CustomeraccountApi customerAccount = new CustomeraccountApi();
                    customerAccount.setAccountId(request.getTrainAccount());
                    customerAccount.setAccountPassword(request.getPass());
                    customerAccount.setAccountType(CustomerConstants.trianAccount.getValue());
                    customerAccount.setCustomerId(Long.valueOf(request.getCustomerId()));
                    customerAccount.setCreateTime(new Date());
                    remoteCustomerService.insert(customerAccount);
                }
            }
        }
        return response;
    }

    //取消改签
    @Override
    public TrCancelChangeResponse trainCancelChange(TrCancelChangeRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.cancel_change_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.cancel_change_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("orderid", request.orderid);
        map.put("reqtoken", request.reqtoken);
        map.put("transactionid", request.transactionid);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrCancelChangeResponse response = JSON.parseObject(post, TrCancelChangeResponse.class);
        return response;
    }

    //确认改签
    @Override
    public TrConfirmChangeResponse confirmChange(TrConfirmChangeRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.confirm_change_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.confirm_change_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("callbackurl", UserUtils.trainConfirmChangeCallback);
        map.put("isasync", request.isasync);
        map.put("transactionid", request.transactionid);
        map.put("orderid", request.orderid);
        map.put("reqtoken", request.reqtoken);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrConfirmChangeResponse response = JSON.parseObject(post, TrConfirmChangeResponse.class);
        return response;
    }

    //线上退票申请
    @Override
    public TrRetreatTicketResponse retreatTicket(TrRetreatTicketRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.ticket_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.ticket_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("callbackurl", UserUtils.returnTicketCallback);
        map.put("orderid", request.orderid);
        map.put("ordernumber", request.ordernumber);
        map.put("reqtoken", request.reqtoken);
        map.put("transactionid", request.transactionid);
        /*map.put("encryptionType", request.encryptionType);
        map.put("LoginUserName", UserUtils.trainAccount);
        map.put("LoginUserPassword", UserUtils.trainPassword);*/
        List<Tickets> list = new ArrayList<>();
        for (Tickets ticket : request.tickets) {
            list.add(ticket);
        }
        map.put("tickets", list);

        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrRetreatTicketResponse response = JSON.parseObject(post, TrRetreatTicketResponse.class);
        return response;
    }

    //改签线上退票申请
    @Override
    public TrRetreatTicketResponse retreatTickets(TrRetreatTicketRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.ticket_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.ticket_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("callbackurl", UserUtils.returnTicketCallbacks);
        map.put("orderid", request.orderid);
        map.put("ordernumber", request.ordernumber);
        map.put("reqtoken", request.reqtoken);
        map.put("transactionid", request.transactionid);
        List<Tickets> list = new ArrayList<>();
        for (Tickets ticket : request.tickets) {
            list.add(ticket);
        }
        map.put("tickets", list);

        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrRetreatTicketResponse response = JSON.parseObject(post, TrRetreatTicketResponse.class);
        return response;
    }

    //查询常用联系人
    @Override
    public TrContactQueryResponse contactQuery(TrContactQueryRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.ContactQuery_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("trainAccount", request.trainAccount);
        map.put("pass", request.pass);
        mapList.add(map);
        Map<String, String> mapParam = new HashMap<>();
        try {
            String data = encodeData(JSON.toJSONString(mapList));
            mapParam.put("data", data);
            mapParam.put("accountversion", "2");
            mapParam.put("trainAccount", request.trainAccount);
            mapParam.put("pass", request.pass);
            mapParam.put("partnerid", UserUtils.partnerID);
            mapParam.put("reqtime", reqtime);
            mapParam.put("method", UserUtils.ContactQuery_method);
            mapParam.put("sign", sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String toJSONString = JSON.toJSONString(mapParam);
        String post = HttpClientUtil.doPostXmlStream(UserUtils.contactQueryUrl, toJSONString);
        TrContactQueryResponse response = JSON.parseObject(post, TrContactQueryResponse.class);
        return response;
    }

    //增加和修改常用联系人（新版）
    @Override
    public TrAddAndUpdateContactsResponse addAndUpdateContacts(TrAddAndUpdateContactsRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("trainAccount", request.trainAccount);
        map.put("pass", request.pass);
        //Contacts contacts = new Contacts();
        Map<String, Object> contactMap = new HashMap<>();
        contactMap.put("id", request.contacts.id);
        contactMap.put("name", request.contacts.name);
        contactMap.put("sex", request.contacts.sex);
        contactMap.put("country", request.contacts.country);
        contactMap.put("identyType", request.contacts.identyType);
        contactMap.put("identy", request.contacts.identy);
        contactMap.put("personType", request.contacts.personType);
        contactMap.put("phone", request.contacts.phone);
        map.put("contacts", contactMap);
        Map<String, String> mapParam = new HashMap<>();
        try {
            String data = encodeData(JSON.toJSONString(map));
            mapParam.put("data", data);
            mapParam.put("accountversion", "2");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String toJSONString = JSON.toJSONString(mapParam);
        String post = HttpClientUtil.doPostXmlStream(UserUtils.addAndUpdateContactsUrl, toJSONString);
        TrAddAndUpdateContactsResponse response = JSONObject.parseObject(post, TrAddAndUpdateContactsResponse.class);
        return response;
    }

    //删除常用联系人
    @Override
    public TrDeleteContactsResponse deleteContacts(TrDeleteContactsRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("trainAccount", request.trainAccount);
        map.put("pass", request.pass);
        map.put("identyType", request.identyType);
        map.put("identy", request.identy);
        map.put("accountversion", "2");
        Map<String, String> mapParam = new HashMap<>();
        try {
            String data = encodeData(JSON.toJSONString(map));
            mapParam.put("data", data);
            mapParam.put("accountversion", "2");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String toJSONString = JSON.toJSONString(mapParam);
        String post = HttpClientUtil.doPostXmlStream(UserUtils.deleteContactsUrl, toJSONString);
        TrDeleteContactsResponse response = JSONObject.parseObject(post, TrDeleteContactsResponse.class);
        return response;
    }

    //获取历史订单
    @Override
    public TrHistoryOrderResponse historyOrder(TrHistoryOrderRequest request) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("trainAccount", request.trainAccount);
        map.put("pass", request.pass);
        mapList.add(map);
        String data = null;
        try {
            data = encodeData(JSON.toJSONString(mapList));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("data", data);
        mapParam.put("accountversion", "2");
        String toJSONString = JSON.toJSONString(mapParam);
        String post = HttpClientUtil.doPostXmlStream(UserUtils.historyOrderUrl, toJSONString);
        TrHistoryOrderResponse response = JSONObject.parseObject(post, TrHistoryOrderResponse.class);
        return response;
    }

    //账户余额查询
    @Override
    public TrQueryMoneyResponse queryMoney() {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.money_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.money_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrQueryMoneyResponse response = JSONObject.parseObject(post, TrQueryMoneyResponse.class);
        return response;
    }

    //注册12306账号
    @Override
    public TrRegisterAccountResponse registerAccount(TrRegisterAccountRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.account_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.account_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("userName", request.userName);
        try {
            map.put("passWord", encrypt(request.passWord, "u0FKpzhZa1x1DeWn"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        map.put("idTypeCode", request.idTypeCode);
        map.put("name", request.name);
        map.put("idNo", request.idNo);
        map.put("email", request.email);
        map.put("passengerType", request.passengerType);
        map.put("mobileNo", request.mobileNo);
        map.put("gatValidDateEnd", request.gatValidDateEnd);
        map.put("gatBornDate", request.gatBornDate);
        map.put("sexCode", request.sexCode);
        map.put("countryCode", request.countryCode);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrRegisterAccountResponse response = JSONObject.parseObject(post, TrRegisterAccountResponse.class);
        return response;
    }

    //短信验证
    @Override
    public TrPhoneMessageValidateResponse phoneMessageValidate(TrPhoneMessageValidateRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.message_validate_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.message_validate_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("userName", request.userName);
        try {
            map.put("passWord", encrypt(request.passWord, "u0FKpzhZa1x1DeWn"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("randCode", request.randCode);
        map.put("validateType", request.validateType);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrPhoneMessageValidateResponse response = JSONObject.parseObject(post, TrPhoneMessageValidateResponse.class);
        return response;
    }

    //找回密码（获取验证码）
    @Override
    public TrRetrievePasswordResponse retrievePassword(TrRetrievePasswordRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.retrievePassword_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.retrievePassword_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("requestid", request.data.requestid);
        dataMap.put("retrievemethod", request.data.retrievemethod);
        dataMap.put("mobileNo", request.data.mobileNo);
        dataMap.put("userpwd", request.data.userpwd);
        dataMap.put("certType", request.data.certType);
        dataMap.put("certNo", request.data.certNo);
        dataMap.put("certTypeName", request.data.certTypeName);
        map.put("data", dataMap);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrRetrievePasswordResponse response = JSONObject.parseObject(post, TrRetrievePasswordResponse.class);
        return response;
    }

    //找回密码（回填验证码）
    @Override
    public TrRetrievePasswordResponse sendcaptcharesult(TrRetrievePasswordRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.sendcaptcharesult_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.sendcaptcharesult_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("requestid", request.data.requestid);
        dataMap.put("userpwd", request.data.userpwd);
        dataMap.put("result", request.data.result);
        map.put("data", dataMap);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrRetrievePasswordResponse response = JSONObject.parseObject(post, TrRetrievePasswordResponse.class);
        return response;
    }

    //重置密码（获取验证码）
    @Override
    public TrResetPasswordResponse resetPassword(TrResetPasswordRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.password_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.password_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("loginName", request.loginName);
        map.put("oldPassword", request.oldPassword);
        map.put("newPassword", request.newPassword);
        map.put("confirmPassword", request.confirmPassword);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrResetPasswordResponse response = JSONObject.parseObject(post, TrResetPasswordResponse.class);
        return response;
    }

    //重置密码（发送验证码）
    @Override
    public TrResetPasswordResponse resetPasswordSend(TrResetPasswordRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.password_send_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.password_send_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("loginName", request.loginName);
        map.put("oldPassword", request.oldPassword);
        map.put("newPassword", request.newPassword);
        map.put("confirmPassword", request.confirmPassword);
        map.put("messageCode", request.messageCode);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrResetPasswordResponse response = JSONObject.parseObject(post, TrResetPasswordResponse.class);
        return response;
    }

    //修改本人账号信息
    @Override
    public TrRetrievePasswordResponse modifyUserInfo(TrRetrievePasswordRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.modifyUserInfo_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.modifyUserInfo_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("username", request.data.username);
        dataMap.put("userpwd", request.data.userpwd);
        dataMap.put("passengerType", request.data.passengerType);
        map.put("data", dataMap);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrRetrievePasswordResponse response = JSONObject.parseObject(post, TrRetrievePasswordResponse.class);
        return response;
    }

    //退票前置核验
    @Override
    public TrRetrievePasswordResponse refundPreCheck(TrRefundPreCheckRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.pre_check_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.pre_check_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        map.put("orderid", request.orderid);
        map.put("extnumber", request.extnumber);
        map.put("callbackurl", UserUtils.refundPreCheckCallback);
        map.put("reqtoken", request.reqtoken);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.orderSubmissionUrl, mapParam);
        TrRetrievePasswordResponse response = JSONObject.parseObject(post, TrRetrievePasswordResponse.class);
        return response;
    }

    //乘客人核验结果查询接口(查询刷新核验状态)
    @Override
    public TrVerificationStatusResponse verificationStatus(TrVerificationStatusRequest request) {
        String keyMd5 = md5(UserUtils.key);
        StringBuilder builder = new StringBuilder();
        builder.append(UserUtils.partnerID);
        builder.append(UserUtils.status_method);
        builder.append(reqtime);
        builder.append(keyMd5);
        String sign = signMsgs(builder.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("partnerid", UserUtils.partnerID);
        map.put("method", UserUtils.status_method);
        map.put("reqtime", reqtime);
        map.put("sign", sign);
        List<PassengersToBeInquireds> list = new ArrayList<>();
        for (PassengersToBeInquireds passenger : request.passengers) {
            list.add(passenger);
        }
        map.put("passengers", list);
        String jsonStr = JSON.toJSONString(map);
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("jsonStr", jsonStr);
        String post = HttpClientUtil.doPost(UserUtils.verificationStatusUrl, mapParam);
        TrVerificationStatusResponse response = JSONObject.parseObject(post, TrVerificationStatusResponse.class);
        return response;
    }

    /**
     * BASE64加密
     */
    private static final String UTF_8 = "UTF-8";

    public static String encodeData(String inputData) throws Exception{
        return new String(Base64.encodeBase64(inputData.getBytes(UTF_8)), UTF_8);
    }



    private final static String DES = "DES";

    /**
     * Description 根据键值进行加密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(UTF_8), key.getBytes(UTF_8));
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }

    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String key) {
        try {
            if (data == null)
                return null;
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] buf = decoder.decodeBuffer(data);
            byte[] bt = decrypt(buf, key.getBytes());
            return new String(bt, "UTF-8");
        } catch (Exception e) {
            return data;
        }

    }

    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

}
